/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/* 
 * Copyright (c) 2009 City University of Hong Kong
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License m_version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * 
 * Author: Wilson Thong (wilsonwk@ee.cityu.edu.hk) 
 */
#ifndef DEFLECTION_ROUTING_H
#define DEFLECTION_ROUTING_H

#include "routing-tools.h"
#include "ns3/random-variable.h"
#include "ns3/ipv4-routing-protocol.h"
#include "ns3/net-device-container.h"
#include "ns3/point-to-point-net-device.h"
#include "ns3/ipv4-header.h"
#include <set>

namespace ns3 {
namespace eecityu {

using namespace std;

/**
 * \brief Implement dynamic deflection routing on top of any routing protocol
 *
 * Ipv4DeflectionRouting object reads a node's status and determine if a packet
 * should be deflected. If no deflection is necessary, Ipv4DeflectionRouting object
 * does not return any routes and let ListRouting to handle this "no route found"
 * event. In other words, a default routing object is necessary when using
 * a Ipv4DeflectionRouting object, and ListRouting must be used for nodes
 *
 * Ipv4DeflectionRouting object uses the node's ListRouting object to find the default
 * out-going exit interface for the packet. Once this exit interface is known,
 * Ipv4DeflectionRouting object then check the node's status, including the status
 * of the default out-going exit interface, and determine if a deflection 
 * is necesary.
 *
 * Note that Ipv4DeflectionRouting object is called twice for each packet routed,
 * the first call is due to the arrival of packets, and the second call is due
 * calling the ListRouting object initalized from the Ipv4DeflectionRouting object
 * itself. In other words, each packet arrived rsults a recurrence calls to
 * the Ipv4DeflectionRouting object's method. In order to prevent recurring calls
 * to Ipv4DeflectionRouting object forever, Ipv4DeflectionRouting object remembers 
 * which packets are in process. If Ipv4DeflectionRouting object is called but
 * the packet is known to be in proecss, this call is a recurrence call,
 * and Ipv4DeflectionRouting object returns "no route" and let the next routing
 * protocol object in the ListRouting object to return a valid route.
 */
class Ipv4DeflectionRouting : public Ipv4RoutingProtocol
{
public:
  static TypeId GetTypeId (void);
  Ipv4DeflectionRouting (void);

  /**
   * \see Ipv4RoutingProtocol::RouteOutput
   */
  Ptr<Ipv4Route> RouteOutput (Ptr<Packet> p, const Ipv4Header &header, Ptr<NetDevice> oif, Socket::SocketErrno &sockerr);
  /**
   * \see Ipv4RoutingProtocol::RouteIutput
   */
  bool RouteInput  (Ptr<const Packet> p, const Ipv4Header &header, Ptr<const NetDevice> idev, 
                             UnicastForwardCallback ucb, MulticastForwardCallback mcb, 
                             LocalDeliverCallback lcb, ErrorCallback ecb);
  /**
   * \see Ipv4RoutingProtocol::RouteOutput
   */
  void NotifyInterfaceUp (uint32_t interface);
  /**
   * \see Ipv4RoutingProtocol::RouteOutput
   */
  void NotifyInterfaceDown (uint32_t interface);
  /**
   * \see Ipv4RoutingProtocol::RouteOutput
   */
  void NotifyAddAddress (uint32_t interface, Ipv4InterfaceAddress address);
  /**
   * \see Ipv4RoutingProtocol::RouteOutput
   */
  void NotifyRemoveAddress (uint32_t interface, Ipv4InterfaceAddress address);
  /**
   * \see Ipv4RoutingProtocol::RouteOutput
   */
  void SetIpv4 (Ptr<Ipv4> ipv4);
  /**
   * \brief Return the priority of the BmsnRouting protocol
   *
   * \return The priority of the BmsnRouting protocol
   */
  int16_t GetPriority () const;

private:
  /**
   * \brief Get the preferred route when there is no deflection
   *
   * It is called in the RouteOutput () method. It obtains a route from the next
   * lower priority routing protocol.
   *
   * For arguments, see Ipv4RoutingProtocol::RouteOutput
   * \return The route from the next lower priority routing protocol
   */
  Ptr<Ipv4Route> LookupPreferredRoute (Ptr<Packet> p, const Ipv4Header &header, Ptr<NetDevice> oif, Socket::SocketErrno &sockerr);
  /**
   * \brief Get the preferred route when there is no deflection
   *
   * It is called in the RouteInput () method. It obtains a route from the next
   * lower priority routing protocol.
   *
   * For arguments, see Ipv4RoutingProtocol::RouteInput
   * \return The route from the next lower priority routing protocol
   */
  Ptr<Ipv4Route> LookupPreferredRoute (
    Ptr<Packet> p, const Ipv4Header &header, Ptr<const NetDevice> idev, 
    UnicastForwardCallback ucb, MulticastForwardCallback mcb, 
    LocalDeliverCallback lcb, ErrorCallback ecb);
  /**
   * \brief Check if the queue of the net device is full
   *
   * \param dev The net device to which a packet is routed
   * \param p The packet to be sent to the net device
   * \return True if the queue has not enough room for the packet; false otherwise
   */
  bool IsQueueFull (Ptr<NetDevice> dev, Ptr<Packet> p) const;
  /**
   * \brief Get the set of net devices whose queue are full
   * \param p The packet to be enqueued into an output net device
   * \return the set of net devices whose queue are full
   */
  NetDeviceContainer GetQueueFullNetDevices (Ptr<Packet> p) const;
  /**
   * \brief Lookup the final route for routing the packet, including
   * the possibility of deflection
   *
   * This method returns the original preferred route if the output queue is not full,
   * or proceed deflecting a packet randomly otherwise. The deflection, if necessary,
   * avoids two output net devices, the input net device and the preferred output
   * net device.
   *
   * \param preferredRoute The preferred route returned from the next lower priority
   * routing protocol
   * \param idev The net device from which the packet comes
   * \param header The IPv4 header of the packet currently being routed
   * \param p The packet currently being routed
   * \return The final route for routing the packet
   */
  Ptr<Ipv4Route> LookupExitRoute (Ptr<Ipv4Route> preferredRoute,
                                  Ptr<const NetDevice> idev,
                                  const Ipv4Header& header,
                                  Ptr<Packet> p);
  /**
   * \brief Get a route randomly but avoid some specified output net devices
   *
   * \param notDevContainer Contain the net devices that must be excluded when 
   * selecting a output net device randomly
   * \param preferred The route returned from the shortest path routing table 
   * \return A route for deflecting a packet
   */
  Ptr<Ipv4Route> DoRandomDeflect (NetDeviceContainer notDevContainer, Ptr<Ipv4Route> preferredRoute);
  /**
   * \param p A packet being routed
   * \return True if this packet is being processed by this routing object; 
   * false otherwise
   */
  bool IsInProcess (Ptr<Packet> p) const;
  /**
   * \param p A in process packet that needs to be remembered by
   * this routing object
   */
  void RememberPacket (Ptr<Packet> p);
  /**
   * \param p A packet for which the associated routing process
   * is finished and this object no long needs to remember this
   * packet as in process
   */
  void ForgetPacket (Ptr<Packet> p);
  /**
   * \brief For making a callback and get the route when routing
   * protocol is calling the unicast forwrd callback
   */
  struct UcbRouteGetter 
  {
    // a UnicastForwardCallback signature
    void Ucb (Ptr<Ipv4Route> r, Ptr<const Packet> p, const Ipv4Header &h);
    Ptr<Ipv4Route> route;
  };

  typedef set<uint32_t> PacketSet_t;
  typedef PacketSet_t::iterator PacketIter_t;
  /**
   * \brief Store the ID of the packets that are now being processed
   */
  PacketSet_t m_inProcessPacketSet;
  /// random number generator for deflecting packets randomly
  UniformVariable m_rand;
  /// The priority among all routing protocol
  int16_t m_priority;
  /// Set to true to allow routing packets back to its incoming interfaces
  bool m_allowRouteBack;
  /**
   * \brief Trace source for every deflection event
   *
   * The trace source has four arguments. 
   * - 1st: The Ipv4Header of the packet current being deflected
   * - 2nd: The packet being deflected
   * - 3rd: The original, prefered out going route for the packet
   * - 4th: The final out going route after deflection
   */
  TracedCallback<const Ipv4Header&, Ptr<const Packet>, Ptr<Ipv4Route>, Ptr<Ipv4Route> > m_deflectionTrace;
  Ptr<Ipv4> m_ipv4;
};

} // namespace eecityu
} // namespace ns3

#endif // #ifndef DEFLECTION_ROUTING_H
